﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using YY.UI;
using YY.UI.BaseDataSvc;
using YY.Common;

namespace YY.UI
{
    public partial class PermissionFrm : BaseFrm
    {
        DataTable _DT = null;
        public PermissionFrm()
        {
            InitializeComponent();
            this.BaseDataProxy = new YY.UI.BaseDataSvc.BaseDataClient();
        }

        private void PermissionFrm_Load(object sender, EventArgs e)
        {
            this.BaseDataProxy.Open();
            Common.BindEnumToComboBox(this.cbBoxRole, typeof(EnumCommon.SysRoleType), new string[] { EnumCommon.SysRoleType.管理员.ToString() }, EnumCommon.SysRoleType.客服员.ToString());
            initDgvColumns();
            initData();
        }

        /// <summary>
        /// 初始化表格列
        /// </summary>
        private void initDgvColumns()
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "id", "id", false, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "moduleKey", "模块关键字", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "moduleName", "模块名称", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "frmId", "所属窗体", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "frmParams", "窗体参数", true, true, null);
            Common.AddDgvColumn(this.dataGridView1, new DataGridViewTextBoxColumn(), "ParamValues", "参数值", false, true, null);

            this.dataGridView2.AutoGenerateColumns = false;
            this.dataGridView2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;//AutoSize十分影响性能
            DataGridViewCheckBoxColumn colCB = new DataGridViewCheckBoxColumn();
            DataGridViewCheckBoxHeaderCell cbHeader = new DataGridViewCheckBoxHeaderCell();
            colCB.HeaderCell = cbHeader;
            Common.AddDgvColumn(this.dataGridView2, colCB, "", "", true, false, null);
            Common.AddDgvColumn(this.dataGridView2, new DataGridViewCheckBoxColumn(), "isRole", "是否角色", true, true, null);
            Common.AddDgvColumn(this.dataGridView2, new DataGridViewTextBoxColumn(), "ownerId", "权限拥有者id", false, true, null);
            Common.AddDgvColumn(this.dataGridView2, new DataGridViewTextBoxColumn(), "", "权限拥有者", true, true, null);
            Common.AddDgvColumn(this.dataGridView2, new DataGridViewTextBoxColumn(), "moduleId", "所属模块id", false, true, null);
            Common.AddDgvColumn(this.dataGridView2, new DataGridViewTextBoxColumn(), "", "所属模块", true, true, null);
            Common.AddDgvColumn(this.dataGridView2, new DataGridViewTextBoxColumn(), "opKey", "操作关键字", true, true, null);
            Common.AddDgvColumn(this.dataGridView2, new DataGridViewTextBoxColumn(), "opName", "操作名称", false, true, null);
            Common.AddDgvColumn(this.dataGridView2, new DataGridViewTextBoxColumn(), "ctrlId", "控件名称", true, true, null);
            Common.AddDgvColumn(this.dataGridView2, new DataGridViewTextBoxColumn(), "ctrlText", "控件文本", true, true, null);

            cbHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked);
        }

        void cbHeader_OnCheckBoxClicked(bool isChecked)
        {
            foreach (DataGridViewRow row in dataGridView2.Rows)
                row.Cells[0].Value = isChecked;
            this.dataGridView2.EndEdit();
        }


        private void initData()
        {
            TB_SysModule[] sysModules = this.BaseDataProxy.FindSysModules(null, null);
            this.dataGridView1.DataSource = sysModules;
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            this._DT = null;
            if (this.cbBoxRole.SelectedItem != null && this.dataGridView1.CurrentRow != null)
            {
                int moduleId = Convert.ToInt32(this.dataGridView1.CurrentRow.Cells[0].Value);
                string moduleName = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
                int ownerId = Convert.ToInt32(Enum.Parse(typeof(EnumCommon.SysRoleType), this.cbBoxRole.Text));
                TB_ActionPermission[] datas = this.BaseDataProxy.FindActionPermissions(true, ownerId, moduleId, null);
                //this.dataGridView2.DataSource = datas;

                string ns = "YY.UI";
                Assembly assem = Assembly.Load(ns);
                Type t = assem.GetType(ns + "." + this.dataGridView1.CurrentRow.Cells[3].Value.ToString());
                Object obj = Activator.CreateInstance(t);


                BaseFrm frm = (BaseFrm)obj;
                List<TB_ActionPermission> list = new List<TB_ActionPermission>();
                loadFrmCtrl(frm.Controls, list);
                this._DT = list.ToDataTable();
                this.dataGridView2.DataSource = this._DT;


                string ownerName = this.cbBoxRole.Text;
                for (int i = 0; i < this.dataGridView2.RowCount; i++)
                {
                    bool isChecked = datas.Any(p => p.ownerId == ownerId && p.moduleId == moduleId && p.opKey == this._DT.Rows[i]["opKey"].ToString() && p.isRole == true);
                    this.dataGridView2.Rows[i].Cells[0].Value = isChecked;
                    this.dataGridView2.Rows[i].Cells[3].Value = ownerName;
                    this.dataGridView2.Rows[i].Cells[5].Value = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();

                }
            }
        }

        private void loadFrmCtrl(Control.ControlCollection ctrls, List<TB_ActionPermission> list)
        {
            int moduleId = Convert.ToInt32(this.dataGridView1.CurrentRow.Cells[0].Value);
            //string moduleName = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
            int ownerId = Convert.ToInt32(Enum.Parse(typeof(EnumCommon.SysRoleType), this.cbBoxRole.Text));

            foreach (Control ctrl in ctrls)
            {
                if (ctrl.HasChildren)
                    loadFrmCtrl(ctrl.Controls, list);

                if (ctrl is ToolStrip)
                {
                    ToolStrip ts = ctrl as ToolStrip;
                    foreach (ToolStripItem tsi in ts.Items)
                    {
                        if (tsi.Tag != null && Enum.IsDefined(typeof(EnumCommon.PermissionOpType), tsi.Tag))
                        {
                            TB_ActionPermission ap = new TB_ActionPermission();
                            ap.ctrlId = tsi.Name;
                            ap.ctrlText = tsi.Text;
                            ap.isRole = true;
                            ap.moduleId = moduleId;
                            ap.opKey = tsi.Tag.ToString();
                            ap.opName = tsi.Tag.ToString();
                            ap.ownerId = ownerId;
                            list.Add(ap);
                        }
                    }
                }
                else if (ctrl is Button)
                {
                    if (ctrl.Tag != null && Enum.IsDefined(typeof(EnumCommon.PermissionOpType), ctrl.Tag))
                    {
                        //bool isChecked = datas.Any(p => p.ownerId == ownerId && p.moduleId == moduleId && p.opKey == ctrl.Tag.ToString() && p.isRole == this.radioButton2.Checked);
                        //this.dataGridView2.Rows.Add(new object[] { isChecked, this.radioButton2.Checked, this.selector1.SelectedValue(), this.selector1.GetComboBoxText(), moduleId, moduleName, ctrl.Tag, ctrl.Tag, ctrl.Name, ctrl.Text });
                        TB_ActionPermission ap = new TB_ActionPermission();
                        ap.ctrlId = ctrl.Name;
                        ap.ctrlText = ctrl.Text;
                        ap.isRole = true;
                        ap.moduleId = moduleId;
                        ap.opKey = ctrl.Tag.ToString();
                        ap.opName = ctrl.Tag.ToString();
                        ap.ownerId = ownerId;
                        list.Add(ap);
                    }
                }
            }

        }

        private void tsBtnSave_Click(object sender, EventArgs e)
        {
            //if (this.selector1.SelectedValue() == null)
            //{
            //    MessageBox.Show("请选择角色或用户成员！");
            //    return;
            //}

            if (this.dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请选择系统模块！");
                return;
            }

            int moduleId = Convert.ToInt32(this.dataGridView1.CurrentRow.Cells[0].Value);
            string moduleName = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
            int ownerId = Convert.ToInt32(Enum.Parse(typeof(EnumCommon.SysRoleType), this.cbBoxRole.Text));

            List<TB_ActionPermission> list = new List<TB_ActionPermission>();
            for (int i = 0; i < this.dataGridView2.RowCount; i++)
            {
                if (Convert.ToBoolean(this.dataGridView2.Rows[i].Cells[0].Value))
                {
                    TB_ActionPermission ap = OTConverter.ConvertToObject<TB_ActionPermission>((this.dataGridView2.Rows[i].DataBoundItem as DataRowView).Row);
                    if (ap != null)
                        list.Add(ap);
                }
            }

            if (this.BaseDataProxy.UpdateActionPermission(ownerId, Convert.ToInt32(this.dataGridView1.CurrentRow.Cells[0].Value), list.ToArray()))
            {
                //this.dataGridView2.DataSource = null;
                MessageBox.Show("保存成功！");
            }
        }

        /// <summary>
        /// checkbox列选中后未提交的，在这里处理提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView2_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (this.dataGridView2.IsCurrentCellDirty) //有未提交的更//改
            {
                this.dataGridView2.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void tsBtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

